package com.ruoyi.project.remake.controller.api;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.AuthUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdCardUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.remake.domain.TCaseMain;
import com.ruoyi.project.remake.domain.TRemake;
import com.ruoyi.project.remake.domain.TRemakeCaseDetails;
import com.ruoyi.project.remake.domain.constant.InitConstant;
import com.ruoyi.project.remake.domain.dto.TCaseMainExcel;
import com.ruoyi.project.remake.domain.enmu.RemakeSourceState;
import com.ruoyi.project.remake.domain.enmu.RemakeStatusState;
import com.ruoyi.project.remake.domain.test.Query;
import com.ruoyi.project.remake.domain.utils.InteractiveUtils;
import com.ruoyi.project.remake.domain.vo.RemakeVo;
import com.ruoyi.project.remake.service.ITCaseMainService;
import com.ruoyi.project.remake.service.ITRemakeCaseDetailsService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 高拍Controller
 *
 * @author ruoyi
 * @date 2020-08-18
 */
@Api("高拍模块接口文档")
@RestController
@RequestMapping("/api/remake/highShot")
public class HighShotController extends BaseController {
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ITCaseMainService tCaseMainService;
    @Autowired
    private ITRemakeCaseDetailsService tRemakeCaseDetailsService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 获取病例分类接口
     *
     * @return
     */
    @ApiOperation("获取病例分类接口")
    @GetMapping("/getCaseClass")
    public AjaxResult list() {
        SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return AjaxResult.success(list);
    }

    /**
     * 获取病例分类接口   使用注解或者代码体内使用测试都可以
     *
     * @return
     */
    @ApiOperation("多数据配置测试demo获取病例分类接口")
    @GetMapping("/dynamicData")
    /* @DataSource(value = DataSourceType.SLAVE)*/
    public AjaxResult dynamicData() {
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
        SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        DynamicDataSourceContextHolder.clearDataSourceType();
        List<SysDictData> list2 = dictDataService.selectDictDataList(dictData);
        list.addAll(list2);
        return AjaxResult.success(list);
    }

    /**
     *
     * @param idCard
     * @return
     */
    @ApiOperation("检查身份证号是否输入有误")
    @GetMapping("/checkIdCard/{idCard}")
    public AjaxResult checkIdCard(@PathVariable String idCard) {
       // boolean result = IdCardUtil.isIdcard(idCard);
        return true ? AjaxResult.success() : AjaxResult.error("身份证不符合要求！");
    }

    /**
     * 新增病例
     *
     * @param tCaseMain
     * @return 返回病例的ID号，并返回保存该病例的路基
     */
    @ApiOperation("保存基本病例")
    @PostMapping("/saveBaseCase")
    public AjaxResult saveBaseCase(@RequestBody TCaseMain tCaseMain) {
        TCaseMain entity = tCaseMainService.selectByCarNumber(tCaseMain.getCardNumber());
        if (null != entity) {
            return AjaxResult.error("病历号不允许重复");
        }

        tCaseMain.setRemakeName(tCaseMain.getUserName());
        return AjaxResult.success(tCaseMainService.creatTCaseMain(tCaseMain));
    }

    /**
     * 查询病例
     *
     * @return 返回病例的编号号，并返回路基
     */
    @ApiOperation("查询病例")
    @PostMapping("/findBaseCase/{cardNumber}")
    public AjaxResult findBaseCase(@PathVariable String cardNumber) {
        TCaseMain tCaseMain = tCaseMainService.selectByCarNumber(cardNumber);
        RemakeVo remakeVo = new RemakeVo();
        BeanUtils.copyProperties(tCaseMain, remakeVo);
        remakeVo.setId(tCaseMain.getId());
        remakeVo.setUrl(tCaseMain.getCardNumber());
        return AjaxResult.success(remakeVo);
    }

    /**
     * 查询病例
     *
     * @return 返回病例的编号号，并返回路基
     */
    @ApiOperation("查询病例")
    @GetMapping("/baseNumber")
    public AjaxResult baseNumber(String cardNumber) {
        TCaseMain tCaseMain = tCaseMainService.selectByCarNumber(cardNumber);
        RemakeVo remakeVo = new RemakeVo();
        BeanUtils.copyProperties(tCaseMain, remakeVo);
        remakeVo.setId(tCaseMain.getId());
        remakeVo.setUrl(tCaseMain.getCardNumber());
        return AjaxResult.success(remakeVo);
    }

    /**
     * 保存图片详情
     *
     * @param tRemakeCaseDetails
     * @return
     */
    @ApiOperation("保存图片详情")
    @PostMapping("/saveRemakeCaseDetails")
    public AjaxResult add(@RequestBody TRemakeCaseDetails tRemakeCaseDetails) {
        tRemakeCaseDetails.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tRemakeCaseDetails.setCreateBy(tRemakeCaseDetails.getUserName());
        tRemakeCaseDetails.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY) + "/" + tRemakeCaseDetails.getImgPath());
        String imgName = tRemakeCaseDetails.getImgName();
        String[] tmp = imgName.split("/");
        imgName = tmp[tmp.length - 1];
        tRemakeCaseDetails.setImgName(imgName);
        Integer maxId=tRemakeCaseDetailsService.getMaxXh(tRemakeCaseDetails);
        tRemakeCaseDetails.setImgXh(null==maxId?1:maxId+1);
        tRemakeCaseDetails = tRemakeCaseDetailsService.insertTRemakeCaseDetails(tRemakeCaseDetails);
        //执行待审核保存
        TCaseMain tCaseMain = new TCaseMain();
        tCaseMain.setId(tRemakeCaseDetails.getCaseMainId());
        tCaseMain.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tCaseMainService.updateTCaseMain(tCaseMain);
        return AjaxResult.success(tRemakeCaseDetails);
    }
    /**
     * 保存图片详情
     *
     * @param tRemakeCaseDetails
     * @return
     */
    @ApiOperation("保存图片详情")
    @PostMapping("/saveRemakeCaseDetailsBath")
    public AjaxResult addBath(@RequestBody List<TRemakeCaseDetails> tRemakeCaseDetails) {
        if(ObjectUtil.isNull(tRemakeCaseDetails)){
            return AjaxResult.success();
        }
        String  pro=configService.selectConfigByKey(InitConstant.PRO_IMG_KEY) + "/";
        List<TRemakeCaseDetails> insertAll= Lists.newArrayList();
        if(tRemakeCaseDetails.size()!=0){
            for(TRemakeCaseDetails details:tRemakeCaseDetails){
                details.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
                details.setCreateBy(details.getUserName());
                details.setImgPath(pro+ details.getImgPath());
                String imgName = details.getImgName();
                String[] tmp = imgName.split("/");
                imgName = tmp[tmp.length - 1];
                details.setImgName(imgName);
                details.setCreateTime(new Date());
                insertAll.add(details);

            }//执行待审核保存
            TCaseMain tCaseMain = new TCaseMain();
            tCaseMain.setId(tRemakeCaseDetails.get(0).getCaseMainId());
            tCaseMain.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
            tCaseMainService.updateTCaseMain(tCaseMain);
        }
        tRemakeCaseDetailsService.saveBath(insertAll);

        return AjaxResult.success();
    }
    /**
     * 上传图片
     *
     * @param baseDir 图片上传路径
     * @param file    图片
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/uploadImg")
    public AjaxResult uploadImg(String baseDir, MultipartFile file) {
        baseDir = RuoYiConfig.getImagedPath() + "/" + baseDir;
        Map<String, String> result = new HashMap<String, String>();
        try {
            String fileName = FileUploadUtils.upload(baseDir, file);
            //为了保证数据的显示，对路径进行了调整。
            result.put("fileName", fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取图片信息地址
     *
     * @param id
     * @return
     */
    @ApiOperation("获取图片信息")
    @GetMapping("/imgDetails/{id}")
    public AjaxResult imgDetails(@PathVariable Long id) {
        TRemakeCaseDetails tRemakeCaseDetails = tRemakeCaseDetailsService.selectTRemakeCaseDetailsById(id);
        SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        for (SysDictData sysDictData : list) {
            if (sysDictData.getDictValue().equals(tRemakeCaseDetails.getClassType())) {
                tRemakeCaseDetails.setClassType(sysDictData.getDictLabel());
            }
        }
        return AjaxResult.success(tRemakeCaseDetails);
    }

    /**
     * 根据病历号获取图片信息地址
     *
     * @param carNumber
     * @return
     */
    @ApiOperation("获取图片信息")
    @GetMapping("/imgDetailsByCarNumber/{carNumber}")
    public AjaxResult imgDetailsByCarNumber(@PathVariable String carNumber) {
        TCaseMain tCaseMain = tCaseMainService.selectByCarNumber(carNumber);
        SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        List<TRemakeCaseDetails> result = tRemakeCaseDetailsService.remakeDetails(tCaseMain.getId(), list.get(0).getDictValue());
        return AjaxResult.success(result);
    }

    /**
     * 病例首页信息初始化回显
     *
     * @param id
     * @return
     */
    @ApiOperation("病例详情信息")
    @GetMapping("/remakeinit")
    public AjaxResult remakeDetails(Long id, String classType, String cardNumber) {
        List<TRemakeCaseDetails> result=null;
        if(null!=id&&null!=classType){
            result = tRemakeCaseDetailsService.remakeDetails(id, classType);
        }
        if (null != cardNumber) {
            TCaseMain tCaseMain = tCaseMainService.selectByCarNumber(cardNumber);
            if (null == tCaseMain) {
                return AjaxResult.success();
            }

/*            SysDictData dictData = new SysDictData();
            dictData.setDictType(Constants.CASE_CLASS);
            List<SysDictData> list = dictDataService.selectDictDataList(dictData);*/
            if (null == classType) {
                result = tRemakeCaseDetailsService.remakeDetails(tCaseMain.getId(), null);
            } else {
                result = tRemakeCaseDetailsService.remakeDetails(tCaseMain.getId(), classType);
            }

        }
        return AjaxResult.success(result);
    }

    /**
     * 病例详情列表
     *
     * @param id
     * @return
     */
    @ApiOperation("病例详情信息")
    @GetMapping("/remarkList")
    public AjaxResult remarkList(Long id) {
        List<TRemakeCaseDetails> result = tRemakeCaseDetailsService.remakeDetails(id, null);
        return AjaxResult.success(result);
    }

    /**
     * 删除翻拍病例图片
     *
     * @param id
     * @return
     */
    @ApiOperation("删除翻拍病例图片")
    @GetMapping("/delDetails/{id}")
    public AjaxResult delDetails(@PathVariable Long id) {
        tRemakeCaseDetailsService.deleteTRemakeCaseDetailsById(id);
        return AjaxResult.success();
    }

    /**
     * 清除
     *
     * @param id
     * @return
     */
    @ApiOperation("清除某一个分类下的翻拍病例图片")
    @GetMapping("/clearDetails")
    public AjaxResult clearDetails(Long id, String classType) {
        tRemakeCaseDetailsService.deleteByClassType(id, classType);
        return AjaxResult.success();
    }

    /**
     * 补拍照片
     *
     * @param tRemakeCaseDetails
     * @return
     */
    @ApiOperation("补拍照片")
    @PostMapping("/retakingImg")
    public AjaxResult retakingImg(@RequestBody TRemakeCaseDetails tRemakeCaseDetails) {
        TRemakeCaseDetails caseDetails = new TRemakeCaseDetails();
        caseDetails.setUpdateBy(tRemakeCaseDetails.getUserName());
        caseDetails.setUpdateTime(new Date());
        caseDetails.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY) + "/" + tRemakeCaseDetails.getImgPath());
        String imgName = tRemakeCaseDetails.getImgName();
        String[] tmp = imgName.split("/");
        imgName = tmp[tmp.length - 1];
        caseDetails.setImgName(imgName);
        caseDetails.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        caseDetails.setId(tRemakeCaseDetails.getId());
        tRemakeCaseDetailsService.updateTRemakeCaseDetails(caseDetails);
        TCaseMain tCaseMain = new TCaseMain();
        tCaseMain.setId(tRemakeCaseDetails.getCaseMainId());
        tCaseMain.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tCaseMainService.updateTCaseMain(tCaseMain);
        return AjaxResult.success();
    }

    /**
     * 插拍照片
     *
     * @param tRemakeCaseDetails
     * @return
     */
    @ApiOperation("插拍照片")
    @PostMapping("/InterphoneImg")
    public AjaxResult InterphoneImg(@RequestBody TRemakeCaseDetails tRemakeCaseDetails) {
        //先保存在修改
        tRemakeCaseDetailsService.InterphoneImg(tRemakeCaseDetails);
        TCaseMain tCaseMain = new TCaseMain();
        tCaseMain.setId(tRemakeCaseDetails.getCaseMainId());
        tCaseMain.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tCaseMainService.updateTCaseMain(tCaseMain);
        return AjaxResult.success();
    }


    /**
     * 根据病历号返回个人信息
     *
     * @param cardNumber
     * @return
     */
    @ApiOperation("病历号返回个人信息")
    @PostMapping("/returnByCardNumber/{cardNumber}")
    public AjaxResult returnByCardNumber(@PathVariable String cardNumber) {
        //先保存在修改

        Map<String, Object> result = InteractiveUtils.basicInform(cardNumber);
        return AjaxResult.success(result);
    }

    /**
     * 根据病历号返回个人信息
     *
     * @param query
     * @return
     */
    @ApiOperation("病历号返回个人信息")
    @GetMapping("/queryByParam")
    public AjaxResult queryByParam(Query query) {
        //先保存在修改
        List<TCaseMain> list = tCaseMainService.queryByParam(query);

        return AjaxResult.success(list);
    }

    /**
     * 病例详情列表
     *
     * @return
     */
    @ApiOperation("病例详情信息")
    @GetMapping("/remarkOtherList/{caseMainId}")
    public AjaxResult remarkOtherList(Long caseMainId) {
        TRemakeCaseDetails details=new TRemakeCaseDetails();
        details.setCaseMainId(caseMainId);
        List<TRemakeCaseDetails> result = tRemakeCaseDetailsService.selectTRemakeCaseDetailsList(details);
        return AjaxResult.success(result);
    }

    /**
     * 农民信息导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */

    @Log(title = "农民信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TCaseMainExcel> util = new ExcelUtil<TCaseMainExcel>(TCaseMainExcel.class);
        List<TCaseMainExcel> farmerExcelList = util.importExcel(file.getInputStream());

        String message = tCaseMainService.importExcel(farmerExcelList);
        return AjaxResult.success(message);
    }
}
